<template>
   <h3>Register</h3>
  <div class="register-container">
    <!-- <a-card class="register-card" title="注册"> -->

    <div class="box-sty">
      <a-spin :spinning="loading" tip="Register, please wait...">
        <div class="register-card">
          <a-form :model="formState" name="register" ref="formRef" @finish="onFinish" :rules="rules" :label-col="labelCol">
            <a-form-item name="first_name" >
              <div  class="form-group">
                <a-input v-model:value="formState.first_name" placeholder="First Name" style="height: 44px;" />
              </div>
            </a-form-item>

            <a-form-item name="last_name" >
              <div  class="form-group">
                <a-input v-model:value="formState.last_name" placeholder="Last Name" style="height: 44px;" />
              </div>

            </a-form-item>

            <a-form-item name="email">
              <a-input v-model:value="formState.email" placeholder="Email" style="height: 44px;">
              </a-input>
            </a-form-item>
            <!-- <div>
              <a-form-item name="email_code">
                <a-input
                  v-model:value="formState.email_code"
                  placeholder="Email verification code"
                  :maxlength="6"
                  class="input-class"
                >
                  <template #suffix>
                    <a-button
                      type="link"
                      :class="['send-btn', { disabled: isCounting }]"
                      :disabled="isCounting"
                      @click.stop="sendVerificationCode"
                    >
                      {{ isCounting ? `${countdown}s` : "Obtain verification code" }}
                    </a-button>
                  </template>
                </a-input>
              </a-form-item>
            </div> -->
            <!--是否有邀请码-->
            <div style="margin-bottom: 15px;font-size: 14px;color: #000000;">
              <a-checkbox v-model:checked="codeChecked" @change="checkboxChange">Invitation Code</a-checkbox>
            </div>
            <a-form-item name="invitation_code"  v-if="codeChecked">
              <a-input v-model:value="formState.invitation_code" placeholder="Invitation Code" style="height: 44px;">
              </a-input>
            </a-form-item>

            <a-form-item name="password" >
              <a-input-password v-model:value="formState.password" placeholder="Password" style="height: 44px;"
                                @input="validatePassword">
              </a-input-password>
            </a-form-item>
            <div class="password-dec">
              <CheckOutlined v-if="isPasswordValid" :style="{fontSize: '17px', color: '#67C23A'}"/>
              <span>At least 8 characters</span>
            </div>
            <div class="password-dec">
              <CheckOutlined v-if="isPasswordComplex" :style="{fontSize: '17px', color: '#67C23A'}"/>
              <span>Contains uppercase and lowercase letters</span>
            </div>

            <a-form-item name="password_confirm" >
              <a-input-password v-model:value="formState.password_confirm" placeholder="Confirm Password" style="height: 44px;"
                                @input="validatePasswordConfirm">
              </a-input-password>
            </a-form-item>
            <div class="password-dec">
              <CheckOutlined v-if="isPasswordConfirmed" :style="{fontSize: '17px', color: '#67C23A'}"/>
              The confirmation password must match the password
            </div>

            <a-form-item name="Contact Telephone"  >
              <PhoneNumberInput
                  class="phone-input-with-border"
                  style="width: 100%;"
                  :initialPhoneNumber="phoneNumber"
                  :initialCountryCode="countryCode"
                  @update:phoneData="updatePhoneData"
              />
            </a-form-item>
            <!-- 谷歌人机验证 -->
            <vue-recaptcha :sitekey="siteKey" size="normal" theme="light" @verify="onVerify" @expire="recaptchaExpired"
                            @fail="recaptchaFailed">6545465565646556</vue-recaptcha>
            <!-- <div class="form-footer">
            <router-link to="/login">已有账号？立即登录</router-link>
          </div> -->
          </a-form>
        </div>
        <a-divider />
        <a-row>
          <a-col :span="24">Tick here to be the first to hear about all Reiss sale and promotional offers, including any
            other
            marketing.</a-col>
        </a-row>
        <a-checkbox v-model:checked="checked" style="margin: 10px 0px;">Email</a-checkbox>
        <a-row>
          <a-col :span="24">We would love to keep in touch by email with the latest information about Reiss
            including news of store and
            sale
            events. You can ask us to stop at any time using the unsubscribe link in all of our messages or by changing
            your
            preferences in 'My Account'. For more information, see our <a href="/privacypolicy" title="Privacy" style="text-decoration: underline;">Privacy and Cookie Policy</a> .</a-col>
        </a-row>
        <a-row :gutter="16" style="margin-top: 20px;">
          <a-col :span="15">
            <!-- <a-checkbox v-model:checked="checked" style="margin: 10px 0px;"></a-checkbox> -->
            By clicking 'Register My Account' you agree to the Terms and Conditions. To find out how we
            process
            your personal information, see our <a href="/privacypolicy" title="Privacy" style="text-decoration: underline;">Privacy and Cookie Policy</a> .</a-col>
          <a-col :span="9">
            <a-button @click="onFinish" type="primary" html-type="submit" block class="submit-sty">Register My Account</a-button>
          </a-col>
        </a-row>


      </a-spin>
    </div>
    <!-- </a-card> -->
  </div>
</template>

<script lang="ts" setup>
import { reactive, ref ,watch,toRaw,onMounted} from 'vue';
import { UserOutlined, LockOutlined ,CheckOutlined} from '@ant-design/icons-vue';
import { message } from 'ant-design-vue';
import { useRouter } from 'vue-router';
import type { Rule } from 'ant-design-vue/es/form';
import { register,getSendCode } from "@/api/user";
import {getSetting} from "@/api/index.ts";
import { Local } from "@/utils/storage.ts";
import PhoneNumberInput from "@/components/PhoneNumberInput.vue";

// reCAPTCHA 组件
import VueRecaptcha from 'vue3-recaptcha2'
interface FormState {
  email: string;
  invitation_code: string;
  code: string;
  // email_code: string;
  email_type:1,
  mobile: string;
  password: string;
  password_confirm: string;
  first_name: string;
  last_name: string;
  g_recaptcha_response: string;
}
const formRef = ref();
const labelCol = { style: { width: '180px' } };
const router = useRouter();
const countdown = ref(0);
const isCounting = ref(false);
const loading = ref(false); // 加载状态
let timer: NodeJS.Timeout | null = null;
const formState = reactive<FormState>({
  email: '',
  invitation_code: '',
  code: '',
  // email_code: '',
  email_type:1,
  mobile: '',
  password: '',
  password_confirm: '',
  first_name: '',
  last_name: '',
  g_recaptcha_response: '',
});

const validateConfirmPassword = async (_rule: Rule, value: string) => {
  if (value !== formState.password) {
    return Promise.reject('Entered passwords differ!');
  }
  return Promise.resolve();
};

const rules: Record<string, Rule[]> = {
  first_name: [
    { required: true, message: 'Please enter your first name' },
  ],
  last_name: [
    { required: true, message: 'Please enter your last name' },
  ],
  email: [
    { required: true, message: 'Please enter your email address' },
    { type: 'email', message: 'Please enter the correct email format' }
  ],
  // email_code:[
  //   { required: true, message: 'Please enter the verification code' },
  // ],

  password: [
    { required: true, message: 'Please enter password', trigger: 'blur' },
    { min: 8, message: 'Password does not meet requirements', trigger: 'blur' },
    {
      pattern: /^(?=.*[a-z])(?=.*[A-Z]).*$/,
      message: 'The password consists of at least eight characters, including uppercase and lowercase letters as well as numbers',
      trigger: 'blur'
    }
  ],

  password_confirm:  [
    { required: true, message: 'Please enter password', trigger: 'blur' },
    { min: 8, message: 'Password does not meet requirements', trigger: 'blur' },
    {
      pattern: /^(?=.*[a-z])(?=.*[A-Z]).*$/,
      message: 'The password consists of at least eight characters, including uppercase and lowercase letters as well as numbers',
      trigger: 'blur'
    }
  ],

};

const startCountdown = () => {
  countdown.value = 60;
  const timer = setInterval(() => {
    countdown.value--;
    if (countdown.value <= 0) {
      clearInterval(timer);
    }
  }, 1000);
};

// watch(() => formState.mobile, (newValue) => {
//   console.log('电话号码更新:', newValue);
//   formState.mobile =newValue;
// });

// watch(() => formState.code, (newValue) => {
//   console.log('国家区号更新:', newValue);
//   formState.code =newValue;
// });
// 区号手机号验证
// 处理手机号和国家代码
const phoneNumber = ref('');
const countryCode = ref('+1');
// 更新手机号数据
const updatePhoneData = (phoneData) => {
  if (phoneData) {
    // 即使手机号无效，也保存当前输入的值
    if (phoneData.isValid) {
      formState.mobile = phoneData.data.phoneNumber;
      formState.code = phoneData.data.countryCode;
      countryCode.value = phoneData.data.countryCode;
    } else {
      // 即使无效也保存当前输入的值，确保用户输入不会丢失
      formState.mobile = phoneData.data.phoneNumber;
      formState.code = phoneData.data.countryCode;
      countryCode.value = phoneData.data.countryCode;
    }
  }
};
// 邮箱验证码发送
const sendVerificationCode = async (event: Event) => {
  event.preventDefault(); // 阻止默认行为

  if (!formState.email) {
    message.warning('Please enter email.');
    return;
  }

  try {
    // 开始倒计时
    isCounting.value = true;
    countdown.value = 60;

    // 清除之前的定时器
    if (timer) {
      clearInterval(timer);
    }

    // 设置新的定时器
    timer = setInterval(() => {
      countdown.value--;
      if (countdown.value <= 0) {
        clearInterval(timer!);
        isCounting.value = false;
      }
    }, 1000);

    const res = await getSendCode(formState.email);
    if (res.code === 200) {
      message.success("Verification code sent successfully");
    } else if (res.code === 40023) {
      message.warning(res.msg);
      // 发送失败时重置倒计时
      clearInterval(timer!);
      isCounting.value = false;
      countdown.value = 0;
    }
  } catch (error) {
    // 发生错误时重置倒计时
    if (timer) {
      clearInterval(timer);
    }
    isCounting.value = false;
    countdown.value = 0;
    message.error("Failed to send verification code");
  }
};
const onFinish = async () => {
  console.log("onFinish", formState);
  formRef.value
      .validate()
      .then(async () => {
        loading.value = true; // 开始加载
        try {
          console.log('values', formState, toRaw(formState));
          const res = await register(toRaw(formState));
          console.log('res', res.code);
          if (res.code === 200) {
            message.success('Registered successfully');
            const savedEmails = JSON.parse(localStorage.getItem('rememberedEmails') || '[]');
            if (!savedEmails.includes(formState.email)) {
              savedEmails.push(formState.email);
              localStorage.setItem('rememberedEmails', JSON.stringify(savedEmails));
            }
            router.push('/login');
          }
        } catch (error) {
          console.log('error', error);
          message.error('Registration failed, please try again');
        } finally {
          loading.value = false; // 结束加载
        }
      })
      .catch(error => {
        console.log('error', error);
      });
};


//拿到网站密钥
const siteKey = ref('')

//获取token发送到后端验证
const onVerify = (token: string) => {
  console.log('Token:', token) // 发送到后端验证
  formState.g_recaptcha_response = token;
}
// 是否有邀请码
const inputDisplay = ref(false)
const codeChecked = ref(false)
const checkboxChange = () => {
  console.log('checkboxChange', codeChecked.value);
  if (codeChecked.value) {
    inputDisplay.value = !inputDisplay.value;
  }
}
const isPasswordValid = ref(false)
const isPasswordComplex = ref(false)
const isPasswordConfirmed = ref(false)
const validatePassword = () => {
  isPasswordValid.value = formState.password.length >= 8;
  isPasswordComplex.value = /^(?=.*[a-z])(?=.*[A-Z]).*$/.test(formState.password);
}

const validatePasswordConfirm = () => {
  isPasswordConfirmed.value = formState.password === formState.password_confirm;
}
const getSiteKey = async () => {
  try {
    const res = await getSetting();
    if (res.code === 200) {
      console.log('res', res.result);
      siteKey.value = res.result.google_site_key;
      Local.set('settingConfig', res.result);
      Local.set('config_timestamp', Date.now());
      Local.set('google_site_key', res.result.google_site_key);
      // return res.result;
    }
  } catch (error) {
    console.error('Failed to get the settings', error);
  }
}
if (!Local.get('settingConfig')) {
  getSiteKey();
} else {
  siteKey.value = Local.get('settingConfig').google_site_key
}
// 在组件挂载时从URL获取邀请码
onMounted(() => {
  // 从URL中获取邀请码参数
  const codeFromUrl = router.currentRoute.value.query.code;

  if (codeFromUrl && typeof codeFromUrl === 'string') {
    // 自动勾选"我有邀请码"
    codeChecked.value = true;
    // 设置邀请码值
    formState.invitation_code = codeFromUrl;
  }
});
</script>

<style lang="scss" scoped>
.send-btn {
  background: #71767f;
  color: white;
  border: none;
  border-radius: 6px;
  cursor: pointer;
  font-size: 0.875rem;
  transition: all 0.3s;

  &:hover {
    background: #000;
    color: #fff;
  }
}

.send-btn.disabled {
  background: #999;
  cursor: not-allowed;
}
.input-class {
  height: 44px;
}
.register-container {
  display: flex;
  justify-content: center;
  margin-top:50px;
  min-height: 100vh;
  background: #ffffff;
  font-size: 12px;
  // min-width: 1200px;
  // padding: 20px;
}

.box-sty {
  width: 460px;
}

.register-card {
  width: 100%;
  max-width: 640px;
}

.form-footer {
  text-align: right;
  margin-top: 16px;
}

.desp-sty {
  /* padding-top: 16px; */
}

.submit-sty {
  background-color: #71767f !important;
  border-radius: 5px !important;
  color: #fff !important;
  font-family: "Nimbus-Sans-L", Arial, Helvetica, sans-serif, Glyphicons Halflings !important;
  font-size: 12px !important;
  font-weight: 700 !important;
  font-stretch: normal;
  font-style: normal;
  height: 44px !important;
  line-height: 14.4px;
  letter-spacing: 1px !important;
  text-align: center;
}

.password-dec {
  color: #606266;
  font-size: 14px;
  margin-bottom: 10px;
  // margin-left: 150px
}

:where(.css-dev-only-do-not-override-1p3hq3p).ant-page-header {
  box-sizing: border-box;
  margin: 0;
  padding: 5px 24px;
  color: rgba(0, 0, 0, 0.88);
  font-size: 12px;
  line-height: 1.5714285714285714;
  list-style: none;
  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, 'Noto Sans', sans-serif, 'Apple Color Emoji', 'Segoe UI Emoji', 'Segoe UI Symbol', 'Noto Color Emoji';
  position: relative;
  background-color: #f7f7f7;
  text-align: center;
}

:where(.css-dev-only-do-not-override-1p3hq3p).ant-page-header .ant-page-header-heading-title {
  margin-right: 12px;
  margin-bottom: 0;
  color: rgba(0, 0, 0, 0.88);
  font-weight: 600;
  font-size: 12px !important;
  line-height: 32px;
  overflow: hidden;
  white-space: nowrap;
  text-overflow: ellipsis;
  text-align: center;
}

@media screen and (max-width: 1280px) {
  .register-container {
    min-width: auto;
    padding: 15px;
  }

  .box-sty {
    width: 100%;
    max-width: 800px;
  }

  .register-card {
    max-width: 100%;
  }

  .password-dec {
    margin-left: 0;
  }

  :where(.css-dev-only-do-not-override-1p3hq3p).ant-page-header {
    padding: 5px 15px;
  }
}

@media screen and (max-width: 768px) {
  .register-container {
    padding: 10px;
  }

  .box-sty {
    max-width: 600px;
  }

  .labelCol {
    width: 120px !important;
  }

  .password-dec {
    font-size: 12px;
  }

  .submit-sty {
    width: 100%;
    height: 48px !important;
    font-size: 14px !important;
  }

  .a-row {
    margin: 0 !important;
  }

  .a-col {
    padding: 0 !important;
  }

  .a-checkbox {
    margin: 10px 0 !important;
  }

  .vue-recaptcha {
    margin-left: 0 !important;
  }
}

/* Update input styles to show only bottom border */
:deep(.ant-input),
:deep(.ant-input-password),
:deep(.ant-input-affix-wrapper) {
  border: none !important;
  border-radius: 0 !important;
  border-bottom: 1px solid #71767f !important;
  box-shadow: none !important;
}

/* Hover styles */
:deep(.ant-input:hover),
:deep(.ant-input-password:hover),
:deep(.ant-input-affix-wrapper:hover) {
  border: none !important;
  border-bottom: 1px solid #333 !important;
  box-shadow: none !important;
}

/* Focus styles */
:deep(.ant-input:focus),
:deep(.ant-input-focused),
:deep(.ant-input-password:focus),
:deep(.ant-input-affix-wrapper:focus),
:deep(.ant-input-affix-wrapper-focused) {
  border: none !important;
  border-bottom: 1px solid #71767f !important;
  box-shadow: none !important;
  outline: none;
}

/* Remove borders from the password suffix icon wrapper */
:deep(.ant-input-password .ant-input-suffix) {
  margin-right: 0;
}

:deep(.ant-input-password .ant-input) {
  border: none !important;
  box-shadow: none !important;
}

/* Apply border styles to PhoneNumberInput component */
:deep(.phone-number-input) {
  border: 1px solid #71767f !important;
  border-radius: 4px !important;
  box-shadow: none !important;
}

:deep(.phone-number-input:hover) {
  border: 1px solid #333 !important;
  box-shadow: none !important;
}

:deep(.phone-number-input:focus),
:deep(.phone-number-input:focus-within) {
  border: 1px solid #71767f !important;
  box-shadow: none !important;
  outline: none;
}

/* Style the phone input fields */
:deep(.phone-number-input .ant-select-selector),
:deep(.phone-number-input input) {
  border: none !important;
  box-shadow: none !important;
}

/* 确保电话输入组件有边框 */
.phone-input-with-border:deep(.ant-input-group-wrapper) {
  border: none !important;
  border-bottom: 1px solid #71767f !important;
  border-radius: 0 !important;
  overflow: hidden;
  display: block !important;
}

.phone-input-with-border:deep(.ant-input-group-addon),
.phone-input-with-border:deep(.ant-input) {
  border: none !important;
  box-shadow: none !important;
}

.phone-input-with-border:deep(.ant-input-group-addon) {
  background-color: transparent;
}

/* 覆盖 ant-design 的输入组样式 */
:deep(.ant-input-group-wrapper) {
  border: none !important;
  border-bottom: 1px solid #71767f !important;
  border-radius: 0 !important;
  overflow: hidden;
}

:deep(.ant-input-group-wrapper:hover) {
  border-bottom: 1px solid #333 !important;
}

:deep(.ant-input-group-wrapper:focus-within) {
  border-bottom: 1px solid #71767f !important;
}

:deep(.ant-input-group .ant-input) {
  border: none !important;
  box-shadow: none !important;
}

:deep(.ant-input-group-addon) {
  border: none !important;
  box-shadow: none !important;
  background-color: transparent !important;
}

:deep(.ant-input-group-addon .ant-select-selector) {
  border: none !important;
  box-shadow: none !important;
}

/* 专门针对email_code验证码输入框 */
:deep(.input-class) {
  border: none !important;
  border-bottom: 1px solid #71767f !important;
  border-radius: 0 !important;
  box-shadow: none !important;
}

:deep(.input-class:hover) {
  border-bottom: 1px solid #333 !important;
}

:deep(.input-class .ant-input) {
  border: none !important;
  border-bottom: none !important;
  box-shadow: none !important;
}

:deep(.input-class .ant-input-suffix) {
  border: none !important;
  box-shadow: none !important;
}

/* 确保所有输入框内部的输入元素没有边框 */
:deep(.ant-input-affix-wrapper .ant-input) {
  border: none !important;
  border-bottom: none !important;
  box-shadow: none !important;
}
</style>
